<template>
  <el-card>
    <div class="welcome">欢迎您登录!</div>
    <el-form ref="loginform" :model="loginform" :rules="formRule">
      <el-form-item label="手机号码" prop="accountNumber">
        <div class="spacing"></div>
        <el-input
          v-model.trim="loginform.accountNumber"
          placeholder="请输入手机号"
          @blur="fillingPassword"
        ></el-input>
      </el-form-item>
      <el-row type="flex" v-if="isVerification" justify="space-between">
        <el-col :span="15">
          <el-form-item label="验证码" prop="verification">
            <el-input v-model.trim="loginform.verification" placeholder="请输入验证码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-button
            :class="{'disabled':isDisable}"
            @click="getVerification"
            type="primary"
            :disabled="isDisable"
          >{{VerificationInfo}}</el-button>
        </el-col>
      </el-row>
      <template v-else>
        <el-form-item label="密码" prop="passWord">
          <el-input v-model.trim="loginform.passWord" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>
         <div class="psw-box">
         <!-- <div>
            <el-checkbox v-model="rememberPwd" @click="rememberfn" class="remember">记住密码</el-checkbox>
          </div>-->
          <router-link to="/login/modify" class="right-link">忘记密码</router-link>
        </div> 
      </template>
    </el-form>

    <el-button @click="formValidate('loginform',login)">登录</el-button>
    <span class="change-button" @click="changeLogin">{{loginMethods}}</span>
    <span class="right-links">
      没有账号?
      <router-link to="/login/register">点击注册</router-link>
    </span>
  </el-card>
</template>
<script>
import { mapState, mapMutations } from "vuex";
//import CookieJs from "@/utils/Cookie.js";
import tokenUtils  from "@/utils/LogIN.js"
import mixin from "@/utils/mixin.js";
import passwordVue from "../modify/password.vue";

export default {
  data() {
      var  isequality1=(rule, value, callback)=>{
          if (/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!\`\<\>\|\_\-\(\)/\@\\#\^\&$%\*-\+=:,\\?\[\]\{}]).{8,18}$/.test(value)) {
              return callback();
          }
          callback(new Error("密码为8-18位，且必须包含数字大小写字母特殊字符"));
      }
    return {
      loginform: {
        accountNumber: "",
        passWord: "",
        verification: "",
      },
      isVerification: true, // 是否验证码登录
      loginMethods: "密码登录", // 登录方式
      rememberPwd: false, // 记住密码
      // 表单验证规则
      formRule: {
        accountNumber: [
          { required: true, message: "请输入手机号码", trigger: "blur" },
          {
            min: 11,
            max: 11,
            message: "请输入正确的手机号码",
            trigger: "blur",
          },
        ],
        verification: [
          { required: true, message: "请输入验证码", trigger: "blur" },
        ],
        passWord: [{ required: true, message: "请输入密码", trigger: "blur" },
//            {
//                min: 8,
//                max: 18,
//                message: "密码长度位8-18位",
//                trigger: "blur",
//            },
            { validator: isequality1, trigger: "blur" }
            ],
      },
      ref: "loginform",
    };
  },
  mixins: [mixin],
  mounted() {
    this.getCookiefn();
  },
  methods: {
    ...mapMutations([
      "setPhoneNumber",
      "setUserId",
      "setUserName",
      "setFinishStatus",
      "setFlat",
    ]),
    //点击记住密码  
    rememberfn() {
      console.log(this.rememberPwd, "记住密码");
      this.rememberPwd = !this.rememberPwd;
    },
    //设置cookie
    setCookiefn(usena, pasw, exday) {
      var exdate = new Date(); //获取时间节点
      exdate.setTime(exdate.getTime() + 24 * 60 * 60 * 1000 * exday); //设置保存时间
      window.document.cookie =
        "userName" + "=" + usena + ";path=/;expires=" + exdate.toGMTString();
      window.document.cookie =
        "password" + "=" + pasw + ";path=/;expires=" + exdate.toGMTString();
    },
    //获取cookie
    getCookiefn() {
      if (document.cookie.length > 0) {
        var arr = document.cookie.split(";");
        console.log(arr);
        for (var i = 0; i < arr.length; i++) {
          var arr2 = arr[i].split("=");
          if (arr2[0] == "userName") {
            this.loginform.accountNumber = arr2[1];
          }
          if (arr2[0] == "password") {
            console.log(arr2[1], "password");
            this.loginform.passWord = arr2[1];
          }
        }
        window.open("../views/Home")
       
      }
      
    },
    //cookie的清除
    clearcookie() {
      this.setCookiefn("", "", -1);
    },
    // 切换登录方式
    changeLogin() {
      if (this.isVerification) {
        this.isVerification = false;
        this.loginMethods = "验证码登录";
        this.loginform.verification = "";
        this.fillingPassword();
      } else {
        this.isVerification = true;
        this.loginMethods = "密码登录";
        this.loginform.passWord = "";
      }
    },
    // 登录
    login() {
      sessionStorage.removeItem("token");
      (this.loginform.verification
        ? this.loginVerification()
        : this.loginPassword()
      ).then(
        ({ data: res }) => {
          if (res.code !== 200) return;
          this.$message.success("登录成功");
          sessionStorage.setItem("token", JSON.stringify(res.data.token));

          this.setUserId(res.data.id);
          this.setPhoneNumber(this.loginform.accountNumber);

          this.setUserName(res.data.username);
          this.setFinishStatus(res.data.finishStatus);
          this.setFlat(res.data.flat);
          this.$router.push("/");
          //判断是否添加到本地缓存
          if (this.rememberPwd) {
            // this.rememberPwd &&
            this.setCookiefn(
              this.loginform.accountNumber,
              this.loginform.passWord,
              2
            );
          } else {
            this.clearcookie("", "", -1);
          }

          // console.log(CookieJs.getCookie(password));
        }
        //        (err) => this.$message.error("网络错误")
      );
    },

    // 获取验证码
    getVerification() {
      if (!/^1[3456789]\d{9}$/.test(this.loginform.accountNumber))
        return this.$message.error("请输入正确的手机号码");
      this.isDisable = true;
      this.$http(
        `/trademark/front/message/appointMsg/${this.loginform.accountNumber}`
      ).then(
        ({ data: res }) => {
          if (res.code !== 200) {
            this.isDisable = false;
            return;
          }
          this.$message.success("验证码发送成功");
          this.VerificationTime();
        },
        (err) => {
          this.isDisable = false;
          //          this.$message.error("网络错误");
        }
      );
    },
    // 验证码登录
    loginVerification() {
      return this.$http("/trademark/front/login", {
        params: {
          phoneNum: this.loginform.accountNumber,
          inputCode: this.loginform.verification,
        },
      });
    },
    // 账号密码登录
    loginPassword() {
      return this.$http.post("/trademark/front/sign", {
        phoneNum: this.loginform.accountNumber,
        password: this.loginform.passWord,
      });
    },

    // 填充密码
    fillingPassword() {
      //      if (CookieJs.getCookie("password")) {
      //        var passArr = CookieJs.getCookie("password").split(
      //          encodeURIComponent("密码")
      //        );
      //        this.loginform.accountNumber == passArr[0] &&
      //          (this.loginform.passWord = passArr[1]);
      //      }
    },
  },
  created() {
    document.addEventListener("keydown", this.keydown);
  },
  beforeDestroy() {
    document.removeEventListener("keydown", this.keydown);
  },
};
</script>
<style lang="less" scoped>
.el-card {
  // width: 25.5rem;
  margin: 0 auto;
  margin-top: 2.5rem;
  padding: 0.5rem;
  color: #333333;
  border-radius: 0.4rem;
  .welcome {
    font-size: 2em;
    font-weight: bold;
    line-height: 2em;
  }
  /deep/ .el-form-item__label {
    margin-bottom: 6px;
  }
  .psw-box {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  .el-form {
    margin-top: 1rem;
    /deep/.el-form-item__label {
      line-height: 1rem;
    }
    /deep/.el-input__inner {
      height: 2.5rem;
    }
    .el-button {
      margin-top: 25px;
      font-size: 1em;
      border: none;
      padding-left: 0;
      padding-right: 0;
      text-align: center;
    }
    .disabled {
      background-color: #999;
    }
  }
  .el-button {
    width: 100%;
    height: 2.5rem;
    background-color: #013d87;
    color: #fff;
    margin-top: 2rem;
    font-size: 1.2em;
  }
  .change-button {
    float: left;
    padding-top: 12px;
  }
  .right-link {
    // float: right;
    position: absolute;
    right: 30px;
    color: #666666;
    a {
      color: #2c9dfc;
    }
  }
  .right-links {
    float: right;
    color: #666666;
    padding-top: 12px;
    a {
      color: #2c9dfc;
    }
  }
  a {
    color: #666666;
  }
  .change-button {
    color: #666666;
    cursor: pointer;
  }
}
</style>
